package com.xm.algorithm;

import java.util.Arrays;

public class TestMe {
    public static void main(String[] args) {
        int[] arr = {11, 12, 22, 25, 34, 64, 90};
        System.out.println(binarySearch(arr, 22));

        int[] arr2 = {64, 11, 22, 90, 25, 12, 34};
        bubbleSort(arr2);
        System.out.println(Arrays.toString(arr2));
    }

    /**
     * 二分法查找 去中间值比较赋值
     * @param arr 整数数组
     * @param target 目标数值
     */
    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 冒泡排序 比较相邻数字大小，创建临时变量替换
     * @param arr 整数数组
     */
    public static void bubbleSort(int[] arr) {
        int len = arr.length;
        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}
